﻿using System;
using System.Collections.Generic;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Geodatabase;

namespace DllShepherd.Core.Esri.Workspace
{
    public class WorkspaceUtils
    {
        #region Const Values

        protected bool IsRecyclingCursorInSearchTable = true;
        private const bool IsRecyclingCursorInGetFeatures = false;
        protected readonly string EmptyWhereClause = String.Empty;

        #endregion Const Values

        /// <summary>
        /// ESRI's IFeatureWorkspace, the class uses this object for all it's actions
        /// </summary>
        protected IFeatureWorkspace Workspace { get; private set; }

        /// <summary>
        /// The only constructor for this class has to receive ESRI's IFeatureWorkspace since it's used in all the actions
        /// </summary>
        /// <param name="workspace"></param>
        public WorkspaceUtils(IFeatureWorkspace workspace)
        {
            Workspace = workspace;
        }

        public bool IsActive()
        {
            try
            {
                return ((IWorkspace)Workspace).Exists();
            }
            catch
            {
                return false;
            }
        }

        protected IFeatureClass GetFeatureClass(string layerName)
        {
            return Workspace.OpenFeatureClass(layerName);
        }

        private IQueryFilter GetQueryFilter(string whereClause)
        {
            return new QueryFilter { WhereClause = whereClause };
        }

        protected List<IFeature> GetLayerFeatures(string layerName)
        {
            var result = new List<IFeature>();
            var filter = GetQueryFilter(EmptyWhereClause);
            var featureClass = GetFeatureClass(layerName);
            using (var comReleaser = new ComReleaser())
            {
                var cursor = featureClass.Search(filter, IsRecyclingCursorInGetFeatures);
                comReleaser.ManageLifetime(cursor);

                var feature = cursor.NextFeature();
                while (feature != null)
                {
                    result.Add(feature);
                    feature = cursor.NextFeature();
                }
            }
            return result;
        }
    }
}
